package com.leen.service.impl;

import com.leen.common.vo.ResponseVO;
import com.leen.dto.TeacherDTO;
import com.leen.entity.Teacher;
import com.leen.repository.TeacherRepository;
import com.leen.service.CrudService;
import com.leen.service.TeacherService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 教师业务逻辑
 *
 * @author admin
 * @date 2021-04-21
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TeacherServiceImpl extends CurdServiceImpl<Teacher,Integer> implements TeacherService {

    private TeacherRepository teacherRepository;

    @Autowired
    public void setTeacherRepository(TeacherRepository teacherRepository) {
        this.teacherRepository = teacherRepository;
        super.setCrudRepository(teacherRepository);
    }


    @Override
    public ResponseVO search(TeacherDTO teacherDTO) {
        Pageable pageable= PageRequest.of(teacherDTO.getPageNumber()-1, teacherDTO.getPageSize());

        Specification<Teacher> specification=new Specification<Teacher>() {
            @Override
            public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> arr=new ArrayList<>();
                if(StringUtils.isNotBlank(teacherDTO.getName())){
                   arr.add(criteriaBuilder.like(root.get("name"), "%" +teacherDTO.getName()+"%"));
                }

                return criteriaBuilder.and( arr.toArray(new Predicate[arr.size()]));
            }
        };

        Page<Teacher> page = this.teacherRepository.findAll(specification, pageable);

        return new ResponseVO(page.getTotalElements(),page.getContent());
    }
}
